## -------------------1------------------
##按要求编写描述符 MyDes：当类的属性被访问、修改或设置的时候，分别做出提醒
##class MyDes:
##    def __init__(self, num, name):
##        self.num = num
##        self.name = name
##
##    def __get__(self, instance, owner):
##        print("正在获取变量： %s " % self.name)
##        return self.num
##
##    def __set__(self, instance, value):
##        print("正在修改变量： %s " % self.name)
##        self.num = value
##
##    def __delete__(self, instance):
##        print("正在删除变量：%s \n 噢~这个变量无法删除~" % self.name)
##
##class Test:
##    x = MyDes(10, 'x')

## -------------------2------------------
##按要求编写描述符 MyDes：记录指定变量的读取和写入操作，并将记录以及触发时间保存到文件：record.txt
##import time as t
##class Record:    
##    def __init__(self, num, name):
##        self.num = num
##        self.name = name
##
##    def __get__(self, instance, owner):
##        f = open('record.txt', 'a', encoding = 'utf-8')
##        str = (" %s 变量与北京时间 %s 被读取, %s = %s"% (self.name, t.asctime(), self.name, self.num))
##        f.write('%s \n' % str)
##        f.close()
##        return self.num
##
##    def __set__(self, instance, value):
##        self.num = value
##        f = open('record.txt', 'a', encoding = 'utf-8')
##        str = (" %s 变量与北京时间 %s 被修改, %s = %s"% (self.name, t.asctime(), self.name, self.num))
##        f.write('%s \n' % str)
##        f.close()
##        return self.num
##
##class Test:
##    x = Record(10, 'x')
##    y = Record(8.8, 'y')

## -------------------3------------------
##编写描述符 MyDes，使用文件来存储属性，属性的值会直接存储到对应的pickle（腌菜，还记得吗？）的文件中。如果属性被删除了，文件也会同时被删除，属性的名字也会被注销。
import pickle as p
import os
class MyDes:
    def __init__(self, name):
        self.name = name
    def __set__(self, instance, value):       
        self.file = open('%s.pkl' % self.name, 'wb')
        self.file_name = '%s.pkl' % self.name
        self.name = value     
        str = ("%s : %s "% (self.name, value))
        p.dump(str, self.file)
        self.file.close()
        
    def __get__(self, instance, owner):
        return self.name
    
    def __delete__(self, instance):
        os.remove(self.file_name)
        
class Test:
    x = MyDes('x')
    y = MyDes('y')
    
    
    
